#!/usr/bin/env bash

s=$(which sleep)

t='<?xml version="1.0" standalone="yes"?>
<tp2package>
<name>test_msg2_pkg3</name>
<version>1.0.0</version>
<description>Test#2 package for postinstall filter</description>
<postinstall>postinst.sh</postinstall>
<files>'

t2='</files>
</tp2package>'

dd=$(dirname $s)
flist=$(ls $dd/s*)
fst_two=$(ls $dd/s* | head -2)
hostname=$(hostname)YY

o=$(whoami)
g=$(id | perl -ne '/.*\((.*?)\).*\((.*?)\).*/; print $2')

if [[ -d tt ]]
then
	rm -rf tt
fi

mkdir tt 
exec >tt/test_01.xml
cp $dd/s* tt
echo "$t"
x=0
for f in $flist
do
	echo "<file perms=\"755\" owner=\"$o\" group=\"$g\">$(basename $f)</file>";
	((x=x+1))
done
echo "$t2"
 
cd tt
exec >postinst.sh
echo "#!/usr/bin/env bash"
echo ""
for cf in $fst_two
do
	echo "echo 'Changes to a file' >>\$PKGROOT/$(basename $cf)"
	echo "echo '=FILE $(basename $cf)' >>\$PKGMSGFILE"
done
echo "exit 0"
exec >/dev/tty

tp2pkg --overwrite --config test_01.xml --verbose --repos /tmp || exit 1

# Remove tt_test_01 namespace if it exists

../../../bin/tp2remove_ns --namespace tt_test_01 --leave

mkdir pkg_root

# Create the new namespace.
../../../bin/tp2make_ns --owner $o --root $PWD/pkg_root --name tt_test_01 --nosqlite || exit 1 

# Install the package.
../../../bin/tp2install --namespace tt_test_01 --pkg test_msg2_pkg3 --verbose --repos /tmp --reinstall  --force
rc=$?

if [[ $rc -ne 0 ]]
then
	echo "Install failed??"
	exit 1
fi

# Check the verification works for the package...

../../../bin/tp2list --namespace tt_test_01 --detail test_msg2_pkg3


../../../bin/tp2verify --namespace tt_test_01 --verbose

rc=$?

if [[ $rc -ne 0 ]]
then
	echo "Failed during verification."
	exit 1
fi

exit 0
